<?php

namespace app\admin\controller\site;

use app\admin\model\AdminRule;
use app\common\controller\Backend;
use app\common\dict\site\SiteAppTypeDict;
use Throwable;

/**
 * 站点套餐
 */
class Group extends Backend
{

    protected string $authMethod = 'allAuthAndOthers';



    /**
     * Group模型对象
     * @var object
     * @phpstan-var \app\admin\model\site\Group
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\site\Group();
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 编辑
     * @param string|null $id
     * @return void
     * @throws Throwable
     */
    public function edit(string $id = null): void
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $this->checkAuth($id);

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        $validate->scene('edit')->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                event('siteGroupUpdate',$row);
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        // 读取所有pid，全部从节点数组移除，父级选择状态由子级决定
        $pidArr = AdminRule::field('pid')
            ->distinct(true)
            ->where('app_type',SiteAppTypeDict::SITE)
            ->where('id', 'in', $row->group_roles)
            ->select()->toArray();

        $group_roles  = is_array($row->group_roles) ? $row->group_roles : explode(',', $row->group_roles);
        foreach ($pidArr as $item) {
            $ruKey = array_search($item['pid'], $group_roles);
            if ($ruKey !== false) {
                unset($group_roles[$ruKey]);
            }
        }
        $row->group_roles = array_values($group_roles);
        $this->success('', [
            'row' => $row,
            'pidArr' => $pidArr
        ]);
    }



    /**
     * 检查权限
     * @param $groupId
     * @return void
     * @throws Throwable
     */
    public function checkAuth($groupId): void
    {
        $authGroups = $this->auth->getAllAuthGroups($this->site_id,$this->authMethod);
        if (!$this->auth->isSuperAdmin($this->site_id) && !in_array($groupId, $authGroups)) {
            $this->error(__($this->authMethod == 'allAuth' ? 'You need to have all permissions of this group to operate this group~' : 'You need to have all the permissions of the group and have additional permissions before you can operate the group~'));
        }
    }


}